package ru.incoremedia.gwttest.application.client.view.user.notesgroup;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.TextBox;
import java.util.ArrayList;
import java.util.List;
import ru.incoremedia.gwttest.core.client.component.autosizedtextarea.HasTextChangeHandler;
import ru.incoremedia.gwttest.core.client.component.autosizedtextarea.TextChangeHandler;


public class GroupNameTextBox extends TextBox implements HasTextChangeHandler {

    public List<TextChangeHandler> textChangeHandlers = new ArrayList<TextChangeHandler>();

    public GroupNameTextBox() {
        addKeyUpHandler(new KeyUpHandler() {
            @Override
            public void onKeyUp(KeyUpEvent event) {
                onTextChange();
            }
        });

        sinkEvents(Event.ONPASTE);
    }

    @Override
    public void onBrowserEvent(Event event) {
        final int eventType = event.getTypeInt();
        switch (eventType) {
            case Event.ONPASTE:
                onTextChange();
                break;
        }
        super.onBrowserEvent(event);
    }

    private void onTextChange() {
        DeferredCommand.addCommand(new Command() {
            @Override
            public void execute() {
                for(TextChangeHandler handler : textChangeHandlers) {
                    handler.onChange();
                }
            }
        });
    }

    @Override
    public void addTextChangeHandler(TextChangeHandler handler) {
        textChangeHandlers.add(handler);
    }

}
